package org.langke.nacos;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.AbstractListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.Yaml;

import javax.annotation.PostConstruct;

/**
 * 同步、获取nacos配置
 */
@Service
@Slf4j
public class NacosConfigCenterService {

    @Value(value = "${nacos.config.data-id}")
    private String dataId;
    @Value(value = "${nacos.config.group}")
    private String group;
    private Yaml yaml = new Yaml();
    private DemoConfig demoConfig;
    @NacosInjected
    ConfigService configService;

    @PostConstruct
    public void init() {
        try{
            String config = configService.getConfig(dataId, group, 3000L);
            log.info("init nacos config:{}",config);
            if(config!=null){
                demoConfig = yaml.loadAs(config, DemoConfig.class);
            }
            //监听配置更新
            configService.addListener(dataId, group, new AbstractListener() {
                @Override
                public void receiveConfigInfo(String config) {
                    log.info("update nacos config:{}",config);
                    try {
                        if(config!=null) {
                            demoConfig = yaml.loadAs(config, DemoConfig.class);
                        }
                    }catch (Exception e){
                        log.error("nacos config update error:",e);
                    }
                }
            });
        }catch (Exception e){
            log.error("nacos config init error:",e);
        }
    }

    public DemoConfig getDemoConfig() {
        return demoConfig;
    }
}
